package com.chenyi.web.controller.shop;

import com.chenyi.common.annotation.Log;
import com.chenyi.common.annotation.UserRequired;
import com.chenyi.common.config.ChenYiConfig;
import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.controller.BaseController;
import com.chenyi.common.core.domain.entity.SysAdmin;
import com.chenyi.common.core.domain.entity.SysShop;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.core.domain.model.LoginShop;
import com.chenyi.common.enums.BusinessType;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.common.utils.AdminUtils;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.common.utils.ShopUtils;
import com.chenyi.file.config.FileConfig;
import com.chenyi.file.utils.FileUploadUtils;
import com.chenyi.framework.web.service.AdminTokenService;
import com.chenyi.framework.web.service.ShopTokenService;
import com.chenyi.shop.service.ISysShopService;
import com.chenyi.system.service.ISysAdminService;
import com.google.common.collect.Maps;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 商户管理Controller
 *
 * @author chenyi
 * @date 2020-10-22
 */
@RestController
@RequestMapping("/shop/profile")
public class ShopProfileController  extends BaseController {

    @Autowired
    private ISysShopService userService;

    @Autowired
    private ShopTokenService tokenService;
    /**
     * 个人信息
     */
    @UserRequired
    @GetMapping
    public ResponseEntity<Object> profile()
    {
        LoginShop loginShop = tokenService.getLoginShop(ServletUtils.getRequest());
        SysShop shop = loginShop.getShop();
        Map<String,Object> data = Maps.newHashMap();
        data.put("data",shop);
//        data.put("roleGroup", userService.selectAdminRoleGroup(loginUser.getUsername()));
        return ResponseEntity.ok(data);
    }

    /**
     * 修改用户
     */
    @UserRequired
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseEntity<Object> updateProfile(@RequestBody SysShop shop)
    {
        if (userService.updateShopProfile(shop) > 0)
        {
            LoginShop loginShop = tokenService.getLoginShop(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginShop.getShop().setNickName(shop.getNickName());
            loginShop.getShop().setPhone(shop.getPhone());
            loginShop.getShop().setEmail(shop.getEmail());
            tokenService.setLoginShop(loginShop);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        throw new BadRequestException("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @UserRequired
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public ResponseEntity<Object> updatePwd(String oldPassword, String newPassword)
    {
        LoginShop loginShop = tokenService.getLoginShop(ServletUtils.getRequest());
        String userName = loginShop.getShop().getUserName();
        String password = loginShop.getShop().getPassword();
        if (!ShopUtils.matchesPassword(oldPassword, password))
        {
            throw new MessageException("修改密码失败，旧密码错误");
        }
        if (ShopUtils.matchesPassword(newPassword, password))
        {
            throw new MessageException("新密码不能与旧密码相同");
        }
        if (userService.resetShopPwd(userName, AdminUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginShop.getShop().setPassword(AdminUtils.encryptPassword(newPassword));
            tokenService.setLoginShop(loginShop);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        throw new BadRequestException("修改密码异常，请联系管理员");
    }


    /**
     * 头像上传
     */
    @UserRequired
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public ResponseEntity<Object> avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            LoginShop loginShop = tokenService.getLoginShop(ServletUtils.getRequest());
            String avatar = FileUploadUtils.upload(ChenYiConfig.getAvatarPath(), file);

            if (FileConfig.getUploadCompress()){
                String uploadUrl = ChenYiConfig.getProfile() + avatar.substring(Constants.RESOURCE_PREFIX.length());
                Thumbnails.of(uploadUrl)
                        .scale(1f)
                        .outputQuality(0.1f)
                        .toFile(uploadUrl);
            }

            if (userService.updateShopAvatar(loginShop.getShop().getUserName(), avatar))
            {
                Map<String,Object> data = Maps.newHashMap();
                data.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginShop.getShop().setAvatar(avatar);
                tokenService.setLoginShop(loginShop);
                return ResponseEntity.ok(data);
            }
        }
        throw new BadRequestException("上传图片异常，请联系管理员");
    }
}
